package com.googlecode.gwtbb.server.service;

import com.googlecode.gwtbb.client.shared.remote.search.SearchPostsBean;
import com.googlecode.gwtbb.client.shared.remote.search.SearchPostsResponse;
import com.googlecode.gwtbb.server.intermediate.search.forum.PostSearcher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.queryParser.ParseException;

import java.io.IOException;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 29, 2008
 */
public class SearchService extends ClientService implements com.googlecode.gwtbb.client.only.remote.search.SearchService {
	private static Log log = LogFactory.getLog(SearchService.class);
	private int maxResultsLimit = 100;
	private PostSearcher postSearcher;

	public PostSearcher getPostSearcher() {
		return postSearcher;
	}

	public void setPostSearcher(PostSearcher postSearcher) {
		this.postSearcher = postSearcher;
	}

	public SearchPostsResponse searchPosts(SearchPostsBean searchPostsBean) {
		SearchPostsResponse retVal = new SearchPostsResponse();
		String queryString = searchPostsBean.getQueryString();
		int maxNumResults = Math.min(searchPostsBean.getMaxResults(), maxResultsLimit);
		try {
			postSearcher.search(retVal, queryString, maxNumResults);
		} catch (IOException e) {
			if (log.isInfoEnabled())
				log.info("received bad queryString: " + queryString);
		} catch (ParseException e) {
			log.error("could not perform search", e);
		}
		return retVal;
	}
}
